﻿using AutoMapper;
using MediatR;
using System.Transactions;
using Traceability.App.API.Application.Command.Basic;
using Traceability.App.Domain.Entities;
using Traceability.App.ErrorCode;
using Traceability.App.Infrastructure.Interface;

namespace Traceability.App.API.Application.Handler.Basic
{
    /// <summary>
    /// 修改溯源基本信息请求命令处理类
    /// </summary>
    public class UpdateBasic_TraceabilityHandler:IRequestHandler<UpdateBasic_TraceabilityCommand,ApiResult<int>>
    {
        IBaseRepository<Basic_Traceability> basicRep;
        IMapper mapper;

        public UpdateBasic_TraceabilityHandler(IBaseRepository<Basic_Traceability> basicRep,  IMapper mapper)
        {
            this.basicRep = basicRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(UpdateBasic_TraceabilityCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();

                var model=basicRep.GetAll().Where(x=>x.Production_Batch==request.production_Batch&&!x.IsDeleted).FirstOrDefault();

                var basicmapper = mapper.Map(request, model);
                basicmapper.Reviser = "李四";
                basicmapper.UpdateTime = DateTime.Now;
                int r = 0;
                
                    r = basicRep.UpdateAsync(basicmapper).Result;

                if (r > 0)
                {
                    res.Msg = "修改成功";
                    res.Code = ApiEnum.Success;
                    res.Data = r;
                }
                else
                {
                    res.Msg = "修改失败";
                    res.Code = ApiEnum.Fail;
                }
                return Task.FromResult(res);



            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
